using AutoMapper;
using Matrix.ServiceDiscovery.Dtos;
using Matrix.ServiceDiscovery.Entities;

namespace Matrix.ServiceDiscovery
{
    /// <summary>
    /// ServiceDiscovery AutoMapper配置
    /// </summary>
    public class MatrixServiceDiscoveryAutoMapperProfile : Profile
    {
        public MatrixServiceDiscoveryAutoMapperProfile()
        {
            // ServiceInfo 映射
            CreateMap<ServiceInfo, ServiceInfoDto>()
                .ForMember(dest => dest.LoadBalancingConfig, opt => opt.MapFrom(src => src.LoadBalancingConfig));

            CreateMap<CreateServiceInfoDto, ServiceInfo>()
                .ConstructUsing(src => new ServiceInfo(
                    Guid.NewGuid(),
                    src.Name,
                    src.Version,
                    src.ServiceType,
                    src.Description,
                    src.ServiceGroup));

            CreateMap<UpdateServiceInfoDto, ServiceInfo>()
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

            // LoadBalancingConfig 映射
            CreateMap<LoadBalancingConfig, LoadBalancingConfigDto>();

            CreateMap<UpdateLoadBalancingConfigDto, LoadBalancingConfig>()
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

            // ServiceInstance 映射
            CreateMap<ServiceInstance, ServiceInstanceDto>()
                .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.Tags))
                .ForMember(dest => dest.Metadata, opt => opt.MapFrom(src => src.Metadata));

            CreateMap<RegisterServiceInstanceDto, ServiceInstance>()
                .ConstructUsing(src => new ServiceInstance(
                    Guid.NewGuid(),
                    src.ServiceId,
                    src.ServiceName,
                    src.InstanceId,
                    src.Host,
                    src.Port,
                    src.Protocol,
                    src.Weight,
                    src.Region,
                    src.Zone));

            // HealthCheckRecord 映射
            CreateMap<HealthCheckRecord, HealthCheckRecordDto>();

            // 反向映射（如果需要）
            CreateMap<ServiceInfoDto, ServiceInfo>()
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

            CreateMap<LoadBalancingConfigDto, LoadBalancingConfig>()
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

            CreateMap<ServiceInstanceDto, ServiceInstance>()
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

            CreateMap<HealthCheckRecordDto, HealthCheckRecord>()
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
        }
    }
}